package com.yimin.floatball

import android.content.DialogInterface
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.os.bundleOf
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.yimin.floatball.databinding.ActivityMainBinding
import com.yimin.floatball.util.AccessibilityUtil

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    private val requestOverlayPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (Settings.canDrawOverlays(this)) {
                startFloatBallService()
            } else {
                Toast.makeText(this, "拒绝了权限┭┮﹏┭┮", Toast.LENGTH_SHORT).show()
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(getContentView())
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        initView()
    }

    private fun getContentView(): View {
        binding = ActivityMainBinding.inflate(layoutInflater)
        return binding.root
    }

    private fun initView() {
        binding.btnStart.setOnClickListener {
            if (!checkAccessibility()) return@setOnClickListener
            if (!checkOverlayPermission()) return@setOnClickListener
            startFloatBallService()
        }
    }

    private fun startFloatBallService() {
        Intent(this, FloatBallService::class.java).apply {
            putExtras(bundleOf("type" to FloatBallService.TYPE_ADD))
        }.also {
            startService(it)
            Log.d(TAG, "startFloatBallService: ")
        }
    }

    private fun checkAccessibility(): Boolean {
        // 判断辅助功能是否开启
        if (!AccessibilityUtil.isAccessibilitySettingsOn(this)) {
            // 引导至辅助功能设置页面
            AlertDialog.Builder(this).apply {
                setTitle("需要打开无障碍")
                setMessage("去设置打开无障碍？")
                setPositiveButton("去设置") { dialog: DialogInterface, which: Int ->
                    dialog.dismiss()
                    startActivity(Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS))
                }
                setNegativeButton("取消") { dialog: DialogInterface, which: Int ->
                    dialog.dismiss()
                }
            }.show()
            return false
        }
        return true
    }

    private fun checkOverlayPermission(): Boolean {
        // min-sdk is 24(> Build.VERSION_CODES.M 23)
        if (!Settings.canDrawOverlays(this)) {
            AlertDialog.Builder(this).apply {
                setTitle("需要悬浮窗权限")
                setMessage("去设置打开权限？")
                setPositiveButton("去设置") { dialog: DialogInterface, which: Int ->
                    dialog.dismiss()
                    val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION).apply {
                        data = Uri.parse("package:$packageName")
                    }
                    requestOverlayPermissionLauncher.launch(intent)
                }
                setNegativeButton("取消") { dialog: DialogInterface, which: Int ->
                    dialog.dismiss()
                }
            }.show()
            return false
        }
        return true
    }
}